package com.okaysoft.ofb

import com.okaysoft.ofb.account.User
import java.text.SimpleDateFormat
import grails.converters.JSON

class ApiController {
   def springSecurityService

    def sysService

    //一、	帐号、密码验证
    def checkUserPass() {
        def userName = params.user
        def password = params.password
        if (!userName || !password) {
            render(contentType:"text/xml",text:"<Info><result>0</result></Info>",encoding:"UTF-8")
            return
        }

        password = springSecurityService.encodePassword(password,userName)
        def user = User.findByUsernameAndPassword(userName,password)
        if (user) {
            render(text:"<Info>" +
                    "<result>1</result>" +
                    "<User>" +
                    "<UserID>${userName}</UserID>" +
                    "<UserName>${user.name}</UserName>" +
                    "<DeptID>${user?.department?.id?:''}</DeptID>" +
                    "<DeptName>${user?.department?.name?:''}</DeptName>" +
                    "</User>" +
                    "</Info>",contentType:"text/xml",encoding:"UTF-8")
            return
        }
        render(text:"<Info><result>0</result></Info>",contentType:"text/xml",encoding:"UTF-8")
    }

    //二、	修改用户密码
    def ChangePassword() {
        def userName = params.UserID
        def oldPass = params.OldPass
        def newPass = params.NewPass
        if (!userName || !oldPass || !newPass) {
            render(text:"<Info><result>0</result><reson>参数不完整</reson></Info>",contentType:"text/xml",encoding:"UTF-8")
            return
        }
        oldPass = springSecurityService.encodePassword(oldPass,userName)
        def user = User.findByUsername(userName)
        if (!user) {
            render(text:"<Info><result>0</result><reson>用户名不正确</reson></Info>",contentType:"text/xml",encoding:"UTF-8")
            return
        }
        if (user.password != oldPass) {
            render(text:"<Info><result>0</result><reson>密码不正确</reson></Info>",contentType:"text/xml",encoding:"UTF-8")
            return
        }
        user.password = newPass
        if (!user.save(flush: true)){
            render(text:"<Info><result>0</result><reson>密码修改失败</reson></Info>",contentType:"text/xml",encoding:"UTF-8")
            return
        }
        render(text:"<Info><result>1</result></Info>",contentType:"text/xml",encoding:"UTF-8")
    }

    //三、	取设备（光交箱）片区树结构信息
    def getPQTree() {
        def userId = params.UserID
        def password = params.Password
       def areas = sysService.areaTreeStr(null)
       render(text: "<Info>$areas</Info>",contentType:"text/xml",encoding:"UTF-8")
    }

    //四、	根据片区ID取该片区下的所有设备（光交箱）基本信息
    def getSBInfoByPQID() {
        def userId = params.UserID
        def password = params.Password
        def pqId = params.PQID
        def result = ''

        if (!pqId) {
            render(text: "<Info><Count>0</Count><SBS>${result}</SBS></Info>",contentType:"text/xml",encoding:"UTF-8")
            return
        }
        def area = Area.get(pqId)
        if (!area) {
            render(text: "<Info><Count>0</Count><SBS>${result}</SBS></Info>",contentType:"text/xml",encoding:"UTF-8")
            return
        }
        def devices = Device.findAllByArea(area)
        devices.each {device->
            result+="<SB>" +
                    "<ID>${device.id}</ID>" +
                    "<Caption>${device.name}</Caption>" +
                    "<Parent>${pqId}</Parent>" +
                    "<MB>${device?.formwork?.id}</MB>" +
                    "<No>${device.code?:''}</No>" +
                    "<XJ>${device.location?.addr?:''}</XJ>" +
                    "<Pos>${device.location?.installation?:''}</Pos>" +
                    "<GPS_X>${device.location?.latitude?:''}</GPS_X>" +
                    "<GPS_Y>${device.location?.longitude?:''}</GPS_Y>" +
                    "<SCCJ>${device.factory?:''}</SCCJ>" +
                    "<XH>${device.model?:''}</XH>" +
                    "<AZFS>${device.mode?.label?:''}</AZFS>" +
                    "<BCRL>${device.capacity?.actual?:''}</BCRL>" +
                    "<SJRL>${device.capacity?.nominal?:''}</SJRL>" +
                    "<AZSJ>${device.date?.format('yyyy-MM-dd')?:''}</AZSJ>" +
                    "<Status>${device.status?.label?:''}</Status>" +
                    "<Remark>${device.description?:''}</Remark>" +
                    "</SB>"
        }
        render(text: "<Info><Count>${devices.size()}</Count><SBS>${result}</SBS></Info>",contentType:"text/xml",encoding:"UTF-8")
    }

    //五、	根据设备（光交箱）ID取该设备（光交箱）基本信息
    def getSBInfoBySBID() {
        def userId = params.UserID
        def password = params.Password
        def sbId = params.SBID
        def result = ''

        if (!sbId) {
            render(text: "<Info><SB></SB></Info>",contentType:"text/xml",encoding:"UTF-8")
            return
        }
        def device = Device.get(sbId)
        if (!device) {
            render(text: "<Info><SB></SB></Info>",contentType:"text/xml",encoding:"UTF-8")
        }
            result+="<SB>" +
                    "<ID>${device.id}</ID>" +
                    "<Caption>${device.name}</Caption>" +
                    "<Parent>${device.area?.id}</Parent>" +
                    "<BoxID>${device.logo?:''}</BoxID>" +
                    "<MB>${device?.formwork?.id}</MB>" +
                    "<No>${device.code?:''}</No>" +
                    "<XJ>${device.location.addr?:''}</XJ>" +
                    "<Pos>${device.location.installation?:''}</Pos>" +
                    "<GPS_X>${device.location.latitude?:''}</GPS_X>" +
                    "<GPS_Y>${device.location.longitude?:''}</GPS_Y>" +
                    "<SCCJ>${device.factory?:''}</SCCJ>" +
                    "<XH>${device.model?:''}</XH>" +
                    "<AZFS>${device.mode?.label?:''}</AZFS>" +
                    "<BCRL>${device.capacity.actual?:''}</BCRL>" +
                    "<SJRL>${device.capacity.nominal?:''}</SJRL>" +
                    "<AZSJ>${device.date?.format('yyyy-MM-dd')}</AZSJ>" +
                    "<Status>${device.status?.label?:''}</Status>" +
                    "<Remark>${device.description?:''}</Remark>" +
                    "</SB>"
        render(text: "<Info>${result}</Info>",contentType:"text/xml",encoding:"UTF-8")
    }

    //六、	根据关键字搜索设备（光交箱），并返回其基本信息
    def getSBInfoBySearch() {
        def userId = params.UserID
        def password = params.Password
        def q = params.Q
        if (!q) {
            render(text: "<Info><Count>0</Count><SBS></SBS></Info>",contentType:"text/xml",encoding:"UTF-8")
            return
        }
        def result = ''
        def query = Device.where {
            name ==~ "%${q}%" || code ==~ "%${q}%" || factory ==~ "%${q}%"
        }
        def total = query.count()
        def devices = query.list()
        devices.each {device->
            result+="<SB>" +
                    "<ID>${device.id}</ID>" +
                    "<Caption>${device.name}</Caption>" +
                    "<Parent>${device.area?.id}</Parent>" +
                    "<MB>${device?.formwork?.id}</MB>" +
                    "<No>${device.code?:''}</No>" +
                    "<XJ>${device.location?.addr?:''}</XJ>" +
                    "<Pos>${device.location?.installation?:''}</Pos>" +
                    "<GPS_X>${device.location?.latitude?:''}</GPS_X>" +
                    "<GPS_Y>${device.location?.longitude?:''}</GPS_Y>" +
                    "<SCCJ>${device.factory?:''}</SCCJ>" +
                    "<XH>${device.model?:''}</XH>" +
                    "<AZFS>${device.mode?.label?:''}</AZFS>" +
                    "<BCRL>${device.capacity?.actual?:''}</BCRL>" +
                    "<SJRL>${device.capacity?.nominal?:''}</SJRL>" +
                    "<AZSJ>${device.date?.format('yyyy-MM-dd')?:''}</AZSJ>" +
                    "<Status>${device.status?.label?:''}</Status>" +
                    "<Remark>${device.description?:''}</Remark>" +
                    "</SB>"
        }
        render(text: "<Info><Count>${total}</Count><SBS>${result}</SBS></Info>",contentType:"text/xml",encoding:"UTF-8")
    }

    //七、	取用户（通信用户）用户组树结构信息
    def getCustomerTree() {
        def userId = params.UserID
        def password = params.Password

        def ts = sysService.clientTreeStr([:])
        render(text: "<Info>${ts}</Info>",contentType:"text/xml",encoding:"UTF-8")
    }

    //八、	根据用户组ID取该用户组下的所有用户信息
    def getCustomerInfoByCID() {
         def cid = params.CID
        if (!cid) {
            render(text: "<Info></Info>",contentType:"text/xml",encoding:"UTF-8")
            return
        }
        def client = Client.get(cid as Long)
        if (!client){
            render(text: "<Info></Info>",contentType:"text/xml",encoding:"UTF-8")
            return
        }
        def clientUsers = ClientUser.findAllByClient(client)
        def count = ClientUser.countByClient(client)
        def str = "<Count>$count</Count>"
        str+="<CustomerS>"
        clientUsers.each {cu->
            str+="<Customer>" +
                    "<ID>${cu.id}</ID>" +
                    "<Caption>${cu.name}</Caption>" +
                    "<Parent>${cid}</Parent>" +
                    "<No>${cu.code?:''}</No>" +
                    "<Remark>${cu.description?:''}</Remark>" +
                    "</Customer>"
        }
        str+="</CustomerS>"
        render(text: "<Info>${str}</Info>",contentType:"text/xml",encoding:"UTF-8")
    }

    //九、	根据用户ID取该用户信息
    def getCustomerInfoByID() {
        def id = params.ID
        if (!id) {
            render(text: "<Info></Info>",contentType:"text/xml",encoding:"UTF-8")
            return
        }
        def cu = ClientUser.get(id)
        if (!cu){
            render(text: "<Info></Info>",contentType:"text/xml",encoding:"UTF-8")
            return
        }
        def str="<Customer>" +
                "<ID>${cu.id}</ID>" +
                "<Caption>${cu.name}</Caption>" +
                "<Parent>${cu.client.id}</Parent>" +
                "<No>${cu.code?:''}</No>" +
                "<Remark>${cu.description?:''}</Remark>" +
                "</Customer>"
        render(text: "<Info>${str}</Info>",contentType:"text/xml",encoding:"UTF-8")
    }

    //十、	根据关键字搜索用户，并返回其基本信息
    def getCustomerInfoBySearch() {
        def q = params.Q
        if (!q){
            render(text: "<Info></Info>",contentType:"text/xml",encoding:"UTF-8")
            return
        }
        def query = ClientUser.where {
            name ==~ "%${q}%" || code ==~ "%${q}%" || description ==~ "%${q}%"
        }
        def clientUsers = query.list()
        def count = clientUsers.size()
        def str = "<Count>$count</Count>"
        str+="<CustomerS>"
        clientUsers.each {cu->
            str+="<Customer>" +
                    "<ID>${cu.id}</ID>" +
                    "<Caption>${cu.name}</Caption>" +
                    "<Parent>${cu.client.id}</Parent>" +
                    "<No>${cu.code?:''}</No>" +
                    "<Remark>${cu.description?:''}</Remark>" +
                    "</Customer>"
        }
        str+="</CustomerS>"

        render(text: "<Info>${str}</Info>",contentType:"text/xml",encoding:"UTF-8")
    }

    //六、	根据设备（光交箱）ID取该设备（光交箱）布局及短端子信息
    def getSBPortInfoBySBID(){
        def sbid = params.SBID
        def userid = params.UserID
        def password = params.Password
        def device = Device.get(sbid as Long)
        if (!device){
            render(text: "<Info></Info>",contentType:"text/xml",encoding:"UTF-8")
            return
        }
        def formwork = device.formwork
        if (!formwork){
            render(text: "<Info></Info>",contentType:"text/xml",encoding:"UTF-8")
            return
        }
        
        def fda = FormworkDetail.findByFormworkAndCategory(formwork,FormworkDetail.Category.A)
        if (!fda){
            render(text: "<Info></Info>",contentType:"text/xml",encoding:"UTF-8")
            return
        }
        def formworkCompositions = fda.formworkCompositions
        def str = ''
        str += '<A>'
        str += "<BJ>${fda.composition}</BJ>"
        str += sysService.getTerminalXml(formworkCompositions,device)
        str += "</A>"
        def fdb =  FormworkDetail.findByFormworkAndCategory(formwork,FormworkDetail.Category.B)
        def formworkCompositionBs = fdb.formworkCompositions
        str += '<B>'
        str += "<BJ>${fdb.composition}</BJ>"
        str += sysService.getTerminalXml(formworkCompositionBs,device)
        str += "</B>"

        render(text: "<Info>${str}</Info>",contentType:"text/xml",encoding:"UTF-8")
    }

    //十二、	根据设备ID取当前设备的任务列表
    def getTasksBySBID (){
         def sbid = params.SBID
        def device = Device.get(sbid as Long)
        if(!device){
            render(text: "<Info></Info>",contentType:"text/xml",encoding:"UTF-8")
            return
        }
        def tasks = Task.findAllByStatusAndDevice(Task.Status.NOTCOMPLETE,device)
        def str = "<Count>${tasks.size()}</Count>"
        str += "<Tasks>"
        tasks.each {t->
            str += "<Task>"
            str += "<ID>${t.id}</ID>"
            str += "<Caption>${t.type?.id?:''}</Caption>"
            def ts = []
            if(t.type?.id == 1) {
                def pair = t.pair
                def pairs = pair.tokenize('|')
                def zg = pairs[0]
                def px = pairs[1]
                def pxs = px.tokenize(',')
                str += "<ZG>${zg}</ZG>"
                pxs.each {p->
                    //str += "<PX>${p}</PX>"
                    def terminal = Terminal.findByDeviceAndTerId(device,p)
                    if(terminal){
                        ts << terminal
                    }

                }
                str += "<PX>${px}</PX>"
                def terminal = Terminal.findByDeviceAndTerId(device,zg)
                if(terminal){
                    ts << terminal
                }
            }else{
                if(t.terminal){
                    def tt = t.terminal?.tokenize(',')
                    tt.each {tter->
                        def terminal = Terminal.findByDeviceAndTerId(device,tter)
                        if(terminal){
                            ts << terminal
                        }
                    }
                }
            }
            if(ts){
                 ts = ts.collect {it.id}
            }
            str += "<Remark>${t.description?:''}</Remark>"
            str += "<CreateTime>${t.assignDate?.format('yyyy-MM-dd')?:''}</CreateTime>"
            str += "<Ports>${ts?ts.join(','):''}</Ports>"
            str += "</Task>"
        }
        str += "</Tasks>"
        render(text: "<Info>${str}</Info>",contentType:"text/xml",encoding:"UTF-8")
    }

    //十三、	增加设备（光交箱）
    def AddSB() {
        def map = [:]
        map.name = params.Caption
        map['area.id'] = params.Parent
        map['formwork.id'] = params.MB
        map.code = params.No
        map.xj = params.XJ
        map['location.installation'] = params.Pos
        map['location.latitude'] = params.Y
        map['location.longitude'] = params.X
        map['factory'] = params.SCCJ
        map['model'] = params.XH
        map['capacity.nominal'] = params.BCRL
        map['capacity.actual'] = params.SJRL
        map['date'] = params.AZSJ?new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(params.AZSJ):new Date()
        map['description'] = params.Remark
        //params.status = params.Status
        def device = new Device(map)

        def ss = Device.Status.values()
        ss.each {s->
            if ("${s.id}" == params.Status) {
                device.status = s
            }
        }
        def mm = Device.Mode.values()
        mm.each {m->
            if ("${m.id}" == params.AZFS) {
                device.mode = m
            }
        }
        if (!device.save(flush: true)){
            log.error(device.errors)
            def str = "<result>0</result>"
            str += "<reson>${device.errors}</reson>"
            render(text: "<Info>${str}</Info>",contentType:"text/xml",encoding:"UTF-8")
            return
        }
        render(text: "<Info><result>1</result></Info>",contentType:"text/xml",encoding:"UTF-8")
    }

    //十四、	修改设备（光交箱）
    def ModifySB(){
        if(!params.SBID){
            def str = "<result>0</result>"
            str += "<reson>Missing argument</reson>"
            render(text: "<Info>${str}</Info>",contentType:"text/xml",encoding:"UTF-8")
            return
        }
        def map =[:]
        def id = params.SBID
        if(params.Caption) {
            map.name = params.Caption
        }
        if (params.Parent){
            map['area.id'] = params.Parent
        }
        if(params.MB){
            map['formwork.id'] = params.MB
        }
        if(params.No){
            map.code = params.No  
        }
        if(params.XJ){
            map.xj = params.XJ
        }
        
        if (params.Logo){
            map.logo = params.Logo
        }
        
        if (params.Pos){
            map['location.installation'] = params.Pos 
        }
        if (params.Y){
            map['location.latitude'] = params.GPS_Y
        }
        if (params.X){
            map['location.longitude'] = params.GPS_X
        }
        if (params.SCCJ)  {
            map['factory'] = params.SCCJ
        }
        if (params.XH){
            map['model'] = params.XH 
        }
        if (params.BCRL) {
            map['capacity.nominal'] = params.BCRL
        }
        if(params.SJRL){
            map['capacity.actual'] = params.SJRL
        }
        if (params.AZSJ) {
            map['date'] = params.AZSJ
        }
        if(params.Remark) {
            map['description'] = params.Remark
        }

        def device = Device.get(id as Long)
        if (!device){
            def str = "<result>0</result>"
            str += "<reson>Device does not exist</reson>"
            render(text: "<Info>${str}</Info>",contentType:"text/xml",encoding:"UTF-8")
            return
        }
        device.properties = map
        if(params.Status){
            def ss = Device.Status.values()
            ss.each {s->
                if ("${s.id}" == params.Status) {
                    device.status = s
                }
            }
        }

        if(params.AZFS)  {
            def mm = Device.Mode.values()
            mm.each {m->
                if ("${m.id}" == params.AZFS) {
                    device.mode = m
                }
            }
        }

        if (!device.save(flush: true)){
            def str = "<result>0</result>"
            str += "<reson>${device.errors}</reson>"
            render(text: "<Info>${str}</Info>",contentType:"text/xml",encoding:"UTF-8")
            return
        }
        render(text: "<Info><result>1</result></Info>",contentType:"text/xml",encoding:"UTF-8")
    }

    /*
    十八、	取所有待办任务列表
     */
    def getAllTasks(){
        def userId = params.UserID
        def password = params.Password
        def tasks = Task.findAllByStatus(Task.Status.NOTCOMPLETE)
        def map = [:]
        def str = ""
        tasks.each {task->
               /* str +="<Task>" +
                        "<ID>${task.id}</ID>" +
                        "<Caption>${task.type?.id}</Caption>" +
                        "<SBID>${task.device?.id}</SBID>" +
                        "<SBCaption>${task.device?.name?:''}</SBCaption>" +
                        "<SBCode>${task.device?.code?:''}</SBCode>" +
                        "<SBAddress>${task.device?.location?.addr?:''}</SBAddress>" +
                        "<Remark>${task.description?:''}</Remark>" +
                        "<CreateTime>${task.assignDate?.format('yyyy-MM-dd')?:''}</CreateTime>" +
                        "</Task>"*/

            def device = task.device
            if(map[device.id]){
                return
            }
            map[device.id]=device.id
            str+="<SB>" +
                    "<ID>${device.id}</ID>" +
                    "<Caption>${device?.name}</Caption>" +
                    "<Parent>${device?.area?.id}</Parent>" +
                    "<MB>${device?.formwork?.id}</MB>" +
                    "<No>${device?.code?:''}</No>" +
                    "<XJ>${device?.location?.addr?:''}</XJ>" +
                    "<Pos>${device?.location?.installation?:''}</Pos>" +
                    "<GPS_X>${device?.location?.latitude?:''}</GPS_X>" +
                    "<GPS_Y>${device?.location?.longitude?:''}</GPS_Y>" +
                    "<SCCJ>${device?.factory?:''}</SCCJ>" +
                    "<XH>${device?.model?:''}</XH>" +
                    "<AZFS>${device?.mode?.label?:''}</AZFS>" +
                    "<BCRL>${device?.capacity?.actual?:''}</BCRL>" +
                    "<SJRL>${device?.capacity?.nominal?:''}</SJRL>" +
                    "<AZSJ>${device?.date?.format('yyyy-MM-dd')?:''}</AZSJ>" +
                    "<Status>${device?.status?.label?:''}</Status>" +
                    "<Remark>${device?.description?:''}</Remark>" +
                    "</SB>"
        }
        render(text: "<Info><Count>${tasks.size()}</Count><SBS>${str}</SBS></Info>",contentType:"text/xml",encoding:"UTF-8")
    }

    def getDBIDByBoxID(){
        def id = params.BoxID
        if (!id) {
            render(text: "<Info><DBID></DBID></Info>",contentType:"text/xml",encoding:"UTF-8")
            return
        }
        def device = Device.findByLogo(id)
        if (!device) {
            render(text: "<Info><DBID></DBID></Info>",contentType:"text/xml",encoding:"UTF-8")
            return
        }
        render(text: "<Info><DBID>${device.id}</DBID></Info>",contentType:"text/xml",encoding:"UTF-8")
    }


    def getDBIDByBoxCode(){
        def code = params.BoxCode
        if(!code){
            render(text: "<Info><DBID></DBID></Info>",contentType:"text/xml",encoding:"UTF-8")
            return
        }
        def device = Device.findByCode(code)
        if (!device) {
            render(text: "<Info><DBID></DBID></Info>",contentType:"text/xml",encoding:"UTF-8")
            return
        }
        render(text: "<Info><DBID>${device.id}</DBID></Info>",contentType:"text/xml",encoding:"UTF-8")
    }

    def setBoxID() {
        def logo = params.DBID
        def id = params.BoxID
        if(!logo || !id){
            render(text: "<Info><result>0</result><reson>参数不完整</reson></Info>",contentType:"text/xml",encoding:"UTF-8")
            return
        }
        def device = Device.get(id as Long)
        if (!device){
            render(text: "<Info><result>0</result><reson>光交箱不存在</reson></Info>",contentType:"text/xml",encoding:"UTF-8")
            return
        }
        device.logo=logo
        if(!device.save(flush: true)){
            render(text: "<Info><result>0</result><reson>绑定失败</reson></Info>",contentType:"text/xml",encoding:"UTF-8")
            return
        }
        render(text: "<Info><result>1</result><reson>绑定成功</reson></Info>",contentType:"text/xml",encoding:"UTF-8")

    }

    //15.	根据端子ID取端子详细信息
    def getPortInfoByID() {
        def id = params.ID
        if (!id){
            render(text: "<Info></Info>",contentType:"text/xml",encoding:"UTF-8")
            return
        }
        def terminal = Terminal.get(id as Long)
        if (!terminal) {
            render(text: "<Info></Info>",contentType:"text/xml",encoding:"UTF-8")
            return
        }
        def st =  terminal?.superiorTerminal

        def superiorTerminal
        def children
        def ts = []
        if(st) {
            superiorTerminal = Terminal.findByNumber(st)
            children = Terminal.findAllBySuperiorTerminal(st)
            ts << superiorTerminal.id
            children.each {ter->
                ts << ter.id
            }
        } else{
            ts << terminal.id
            children = Terminal.findAllBySuperiorTerminal(terminal.number)
            children.each {ter->
                ts << ter.id
            }
        }
        def str = '<Port>'
        str += "<ID>${terminal.id}</ID>"
        str += "<letter>${terminal.letter?:''}</letter>"
        str += "<letterNumber>${terminal.letterNumber?:''}</letterNumber>"
        str += "<logo>${terminal.logo?:''}</logo>"
        str += "<status>${terminal.status?.id?:''}</status>"
        str += "<opening>${terminal.opening?:''}</opening>"
        str += "<segmentName>${terminal.segmentName?:''}</segmentName>"
        str += "<opticalNumber>${terminal.opticalNumber?:''}</opticalNumber>"
        str += "<backboneWiring>${terminal.backboneWiring?.id?:''}</backboneWiring>"
        str += "<jumper>${ts.join(',')?:''}</jumper>"
        str += "<description>${terminal.description?:''}</description>"
        str += "</Port>"
        render(text: "<Info>${str}</Info>",contentType:"text/xml",encoding:"UTF-8")
    }
    
    def terminal(){
        def id = params.id
        def terminal = Terminal.get(id as Long)
        def superTerminal
        def children = []
        def json = [:]
       // if (terminal && terminal.superiorTerminal) {
            if (terminal) {
                if(terminal.superiorTerminal){
                    superTerminal = Terminal.findByNumber(terminal?.superiorTerminal)

                }
                if(terminal.backboneWiring == Terminal.BackboneWiring.WIRING) {
                    children = Terminal.findBySuperiorTerminal(terminal.number)
                }else{
                    children = Terminal.findAllBySuperiorTerminal(terminal.number)
                }
                if(superTerminal) {
                    if (children){
                        children += Terminal.findAllBySuperiorTerminal(superTerminal.number)
                    } else{
                        children = Terminal.findAllBySuperiorTerminal(superTerminal.number)
                    }
                }else{
                    superTerminal = terminal
                }
            }

            json = [id:terminal?.id?:'',code:terminal?.number?:'',jk:terminal?.area?terminal?.area[1]:'',district:terminal?.area?terminal?.area[0]:'',letter:terminal?.letter?:'',letterNumber:terminal?.letterNumber?:'']
            json.logo = terminal?.logo?:''
            json.status = terminal?.status?.id?:''
            json.opening = terminal?.opening?:''
            json.segmentName = terminal?.segmentName?:''
            json.opticalNumber = terminal?.opticalNumber?:''
            json.backboneWiring = "${terminal?.backboneWiring?.id?:''}"
            json.logo = terminal?.logo?:''
            def last = [id:superTerminal?.id?:'',code:superTerminal?.number?:'',jk:superTerminal?.area?superTerminal?.area[1]:'',district:superTerminal?.area?superTerminal?.area[0]:'',letter:superTerminal?.letter?:'',letterNumber:superTerminal?.letterNumber?:'']

            last.tqh = superTerminal?.tiaoQianCode?:''
            last.logo = superTerminal?.logo?:''
            last.description = superTerminal?.description?:''
            last.status = superTerminal?.status?.id?:''
            last.opening=superTerminal?.opening?:''
            last.segmentName = superTerminal?.segmentName?:''
            last.opticalNumber = superTerminal?.opticalNumber?:''
            json.ZG = last
            def spl = [:]
            spl.splitter = terminal?.splitter?:''
            spl.splitterModel = terminal?.splitterModel?:''
            spl.splitRatio = terminal?.splitRatio?:''
            if(spl.splitter)  {
                json.FG = spl
            }else{
                json.FG = [splitter:false]
            }
            json.description = terminal?.description?:''
            //if(terminal?.backboneWiring == Terminal.BackboneWiring.WIRING) {
            // //   def next = [SBID:children?.device?.id?:'',SBCode:children?.device?.code?:'',SBCaption:children?.device?.name?:'',PortID:children?.id?:'',PortCode:children?.number?:'',Portjk:children?.area?children?.area[1]:'',Portletter:children?.letter?:'',PortletterNumber:children?.letterNumber?:'']
            //    json.PX = next
            //} else{
                def nextlist = children.collect {ter->
                    def njson = ["id":ter.id?:'',"code":ter.number?:'',"jk":ter.area?ter.area[1]:'',district:ter?.area?ter?.area[0]:'',"letter":ter.letter?:'',"letterNumber":ter.letterNumber?:'',"tqh":ter.tiaoQianCode?:'',"port":ter.jumperPort?:'',status: ter?.status?.id?:'']
                    njson.opening=ter?.opening?:''
                    njson.segmentName = ter?.segmentName?:''
                    njson.opticalNumber = ter?.opticalNumber?:''
                    njson.description = ter?.description?:''
                    return njson
                }
                json.PX = nextlist
            //}
       // }
        render(view: '/webview/terminal',model: [terminal:terminal,terminalJson:(json as JSON)as String])
    }
    
    def task(){
        def id = params.id
        def t = Task.get(id as Long)
        def zg
        def pxs
        def device = t?.device
        def ts = [id:device?.id]
        if (t?.type == Task.Type.JUMPING) {
            def pair = t.pair
            def ps = pair.tokenize('|')
            zg = ps[0]
            zg = Terminal.findByDeviceAndTerId(device,zg)
            def area = zg.area
            ts.ZG = [id:zg.id,district:area[0],jk: area[1],letter:zg.letter,letterNumber:zg.letterNumber]
            pxs = ps[1].tokenize(',')

            pxs = pxs.collect {p->
                def px = Terminal.findByDeviceAndTerId(device,p)
                def parea = px.area
                return [id:px.id,district: parea[0],jk: parea[1],letter:px.letter,letterNumber:px.letterNumber]
            }
            //println(pxs)
            ts.PX = pxs
        }
        render(view:'/webview/operate_task',model:[ts:(ts as JSON) as String,task:t,zg:zg,pxs:pxs])
    }
    
    def user(){
        def id = params.id
        def user = ClientUser.get(id as Long)
        def ut = user?.clientUserTypes?.collect {it.type.label}
        def terminalClientUser
        if(user){
            terminalClientUser = TerminalClientUser.findByClientUser(user)
        }
        render(view: '/webview/user',model: [user:user,userType:ut?ut.join(','):'',terminal: terminalClientUser?.terminal])
    }

    def clientUser() {
        def number = params.number
        def terminal = Terminal.findByNumber(number)
        def clientUsers = terminal?.clientUsers
        clientUsers = clientUsers.collect {cu->
            def cut = cu.clientUserTypes
            cut = cut.collect {c->
                c.type.label
            }
            [id: cu.id,text:cu.name,name:cu.name,vip:cu.vip,type:cut?.join(','),code: cu.code,description: cu.description,'client.id':cu.client?.id,clientId:cu.client?.id,clientName:cu.client?.name]
        }
        render(view:'/webview/terminalClientUser',model:[clientUsers:clientUsers?:[],total:clientUsers?clientUsers.size():0])
    }

    def router(){
        def number = params.number
        if(!number){
            render(view:'/device/route',model:[routes:[]])
            return
        }
       
        def terminal = Terminal.findByNumber(number)
        if(!terminal){
            render(view:'/device/route',model:[routes:[]])
            return
        }
        def list = sysService.getUpNetRouter(terminal,true)
        def downList = sysService.getDowngetNetRouter(terminal)
        render(view:'/device/route',model:[routes:downList+list])
    }

    def clientUserRouter(){
        def id = params.id
        def user = ClientUser.get(id as Long)

        def terminalClientUser
        if(user){
            terminalClientUser = TerminalClientUser.findByClientUser(user)
        }

        def terminal = terminalClientUser?.terminal
        if(!terminal){
            render(view:'/device/route',model:[routes:[]])
            return
        }
        def list = sysService.getUpNetRouter(terminal,true)
        def downList = sysService.getDowngetNetRouter(terminal)
        render(view:'/device/route',model:[routes:downList+list])
    }
    
    def taskComplete() {

        def id = params.id
        if (!id){
            def result = [status: 0] as JSON
            render(result.toString())
            return
        }
        def task = Task.get(id as Long)
        if (!task){
            def result = [status: 0] as JSON
            render(result.toString())
            return
        }
        task.status = Task.Status.COMPLETE
        task.result = params.result
        if (!task.save(flush: true)){
            def result = [status: 0] as JSON
            render(result.toString())
            return
        }
        def result = [status: 1] as JSON
        render(result.toString())
    }

    def taskResult() {
        /*def id = params.id
        def t = Task.get(id as Long)
        def zg
        def pxs
        def device = t?.device
        def ts = [id:device?.id]
        if (t?.type == Task.Type.JUMPING) {
            def pair = t.pair
            def ps = pair.tokenize('|')
            zg = ps[0]
            zg = Terminal.findByDeviceAndTerId(device,zg)
            def area = zg.area
            ts.ZG = [id:zg.id,district:area[0],jk: area[1],letter:zg.letter,letterNumber:zg.letterNumber]
            pxs = ps[1].tokenize(',')

            pxs = pxs.collect {p->
                def px = Terminal.findByDeviceAndTerId(device,p)
                def parea = px.area
                return [id:px.id,district: parea[0],jk: parea[1],letter:px.letter,letterNumber:px.letterNumber]
            }
            //println(pxs)
            ts.PX = pxs
        }*/
        render(view:'/webview/task',model:[msg:'该任务已经完成'])
    }

    def saveTask() {
        def taskId = params.long('taskId')
        def zgId = params.long("zgId")
        def zgfgq = params.zgfgq
        def zffgb = params.zgfgb
        def fgq = params.fgq
        def pxIds = params.pxId
        def pxfgq = params.pxfgq
        def sm = params.sm

        pxIds = pxIds.tokenize(",")
        pxfgq = pxfgq.tokenize(',')
        
        def task = Task.get(taskId)
        if (!task) {
            render(([status: 0] as JSON) as String)
            return
        }
        
        if (task.status == Task.Status.COMPLETE) {
            render(([status: 2,msg:'该任务已经完成'] as JSON) as String)
           // render(view: '/webview/task',model: [msg:'该任务已经完成'])
            return
        }
        
        task.status = Task.Status.COMPLETE
        if(!task.save(flush: true)){
            render(([status: 0] as JSON) as String)
            return
        }

        def zg = Terminal.get(zgId)
        if (!zg) {
            render(([status: 0] as JSON) as String)
            return 
        }
        pxIds.eachWithIndex {ele,i->
            def ter = Terminal.get(ele as Long)
            if (!ter) {
                return
            }
            ter.opticalSplitterPorts = pxfgq[i]
            ter.status = Terminal.Status.JUMPER
            ter.superiorTerminal=zg.number
            ter.save(flush: true)
        }
        if (fgq == '1') {
            zg.splitter=true
            zg.splitterModel=zgfgq
            zg.splitRatio=zffgb
        } else{
            zg.splitter=false
            zg.splitterModel=''
            zg.splitRatio=''
        }
        zg.description= sm
        zg.status = Terminal.Status.JUMPER
        if(!zg.save(flush: true) ){
            render(([status: 0] as JSON) as String)
            return
        }
        render(([status: 1,msg:'该任务已经完成'] as JSON) as String)
        //render(view: '/webview/task',model: [msg:'该任务已经完成'])
    }

}
